package com.cy.util;

import com.cy.pojo.RedisLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockUtils {
	private static final Logger logger = LoggerFactory.getLogger(LockUtils.class);
	static ThreadLocal<String> thred = new ThreadLocal<String>();
	public static ConcurrentHashMap<String, RedisLock> lockMap = new ConcurrentHashMap();
	private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(false);

	public LockUtils(){}
	    /**
	     * 获取锁
	     * @param key
	     * @return
	     */
	    public static RedisLock getALock(String key) {
			try {
				lock.readLock().lock();
				RedisLock rl = (RedisLock) lockMap.get(key);
				lock.readLock().unlock();
				lock.writeLock().lock();
				if (rl == null) {
					rl = new RedisLock(key);
					lockMap.put(key, rl);
				} else {
					rl.addNum(1);
				}
				lock.writeLock().unlock();
				return rl;
			}catch (Exception e){
				lock.readLock().lock();
				lock.writeLock().unlock();
				logger.info("======================锁炸了===============================" + e.getMessage());
			}
			return null;
	    }

	    /**
	     * 释放锁
	     * @param key
	     */
	    public static void returnALock(String key) {
			try {
				lock.readLock().lock();
				RedisLock rl = (RedisLock) lockMap.get(key);
				if (rl.showNum() <= 1) {
					lock.readLock().unlock();
					lock.writeLock().lock();
					lockMap.remove(key);
					lock.writeLock().unlock();
				} else {
					lock.readLock().unlock();
					lock.writeLock().lock();
					rl.addNum(-1);
					lock.writeLock().unlock();
				}
			}catch (Exception e){
				lock.readLock().lock();
				lock.writeLock().unlock();
				logger.info("======================释放锁炸了===============================" + e.getMessage());
			}
	    }
}

